{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 143 Precipitation Timelapse animation\n",
    "\n",
    "This notebook demonstrates how to generate the timelapse animation of [IMERG precipitation dataset](https://developers.google.com/earth-engine/datasets/catalog/NASA_GPM_L3_IMERG_V06). In the animation, you can add map elements such as, title of map, north arrow, map scale, colorbar etc."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# !pip install .\n",
    "# !pip install cartopy scipy"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "gfIaalF8mDyr"
   },
   "outputs": [],
   "source": [
    "import geemap\n",
    "import ee\n",
    "\n",
    "ee.Authenticate()\n",
    "ee.Initialize(project=\"YOUR-PROJECT-ID\")\n",
    "\n",
    "print(geemap.__version__)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 17
    },
    "id": "8blkLEBTovtH",
    "outputId": "018d35cc-7cb5-4e8a-c86d-c924b7dca8db"
   },
   "outputs": [],
   "source": [
    "m = geemap.Map(center=(0.7893, 113.9213), zoom=5)\n",
    "m"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 17
    },
    "id": "aI8ziFsH1dUO",
    "outputId": "cae8d938-db0c-4a9f-d863-f9a986f9be59"
   },
   "outputs": [],
   "source": [
    "# Extract the required country boundary, in this case Indonesia\n",
    "countries = ee.FeatureCollection(\"FAO/GAUL/2015/level0\")\n",
    "indonesia = countries.filter(ee.Filter.eq(\"ADM0_NAME\", \"Indonesia\"))\n",
    "indonesia_geom = indonesia.geometry()\n",
    "\n",
    "# Load the IMERG precipitation data for the desired day\n",
    "date = ee.Date(\"2023-07-15\")\n",
    "precipitation_collection = ee.ImageCollection(\"NASA/GPM_L3/IMERG_V06\").filterDate(\n",
    "    date, date.advance(1, \"day\")\n",
    ")\n",
    "\n",
    "\n",
    "# Define a function to mask out precipitation less than 0.5 mm/hr\n",
    "def mask_less_ppt(collection):\n",
    "    masked_collection = collection.map(lambda image: image.updateMask(image.gte(0.5)))\n",
    "    return masked_collection\n",
    "\n",
    "\n",
    "# Mask out precipitation less than 0.5 mm/hr\n",
    "masked_imerg_collection = mask_less_ppt(precipitation_collection)\n",
    "\n",
    "# add indonesia boundary to map\n",
    "style = {\"color\": \"000ffff0\", \"width\": 2, \"lineType\": \"solid\", \"fillColor\": \"00000000\"}\n",
    "m.addLayer(indonesia.style(**style), {}, \"Indonesia_boundary\")\n",
    "\n",
    "\n",
    "# Define visualization parameters\n",
    "palette = [\n",
    "    \"000096\",\n",
    "    \"0064ff\",\n",
    "    \"00b4ff\",\n",
    "    \"33db80\",\n",
    "    \"9beb4a\",\n",
    "    \"ffeb00\",\n",
    "    \"ffb300\",\n",
    "    \"ff6400\",\n",
    "    \"eb1e00\",\n",
    "    \"af0000\",\n",
    "]\n",
    "vis_params = {\n",
    "    \"min\": 0,\n",
    "    \"max\": 50,\n",
    "    \"bands\": \"precipitationCal\",\n",
    "    \"palette\": [\"000096\", \"0064ff\", \"00b4ff\", \"eb1e00\", \"af0000\"],\n",
    "}\n",
    "\n",
    "# # Add the precipitation data to the map\n",
    "# m.addLayer(masked_imerg_collection, vis_params, 'Precipitation (IMERG)')\n",
    "# m"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 34
    },
    "id": "Vg8-r_Fp3r9L",
    "outputId": "38ecd571-7f51-45d9-833a-f4bc84ec1155"
   },
   "outputs": [],
   "source": [
    "# clip the precipitation data to the Indonesia boundary\n",
    "clipped_imerg_collection = masked_imerg_collection.map(\n",
    "    lambda image: image.clip(indonesia_geom)\n",
    ")\n",
    "\n",
    "# Get the number of images in the clipped collection\n",
    "clipped_imerg_collection.size().getInfo()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# get bounding box of indonesia\n",
    "indonesia_bbox = indonesia.geometry().bounds()\n",
    "indonesia_bbox"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 621,
     "referenced_widgets": [
      "2952dc12a05e45278d9969a91be36492",
      "ec348b1bf50e49c39a95b0289b5c4ed3",
      "7c0402002b9a4cffad4c3facffb836f5",
      "2e4d9d028d664db8803a299622d325a8",
      "d74cefca8e7342d0bf4bfec82d950a37",
      "a3d948531a284add98b53e3445b656c2",
      "c1561443bf0a41ff91f4f4b32fc05c6d",
      "064935c3fc1d4d1891c4cbde8f5cea6f",
      "287370394fd7412cb098607eefb23169",
      "258c0ab53e814200bf29ddf16bf1a3b4",
      "2a39453c61764e23a04e17676ea7835b",
      "c0674084929344798b374312cce920d0",
      "e0dea0e06429409db7fd9ed03a8e53cd",
      "e2b9a631eee949d88f7bb2c456c6f0b9",
      "59e0a90e32cd4e26b444d7aa9e44ac8b",
      "131b72e979ac43749e025e41102f90bc",
      "e462540353514b928662fc23cbc47c21",
      "b434aeebecb64f8babe68813eb603fe9",
      "b5d9b9a3537344b0beef88668e7387b6",
      "db459ec8e602476f86791eb6caa80d13",
      "96c55adfb75446b3907dfb3daf9d8008",
      "5099ac22c8104a17bd568275781cc595",
      "b6e337a2d1c84447ad6f0277e728770f",
      "3c7da3fa4f6342329e5ad3ae17ed832a",
      "393052727f614873a7c1fdefcbd5e1ee",
      "d430fcbb1e8a405cb51bfa2ead4ea984",
      "d302bad52d0c47259dec786204bee003",
      "6e87255caf394630ae47d1d2373bc94e"
     ]
    },
    "id": "pXPxdzwd2SSi",
    "outputId": "6c65df7c-aedc-460b-9f50-432b51fd1921"
   },
   "outputs": [],
   "source": [
    "# Display sample image\n",
    "vis_params = {\n",
    "    \"min\": 0,\n",
    "    \"max\": 50,\n",
    "    \"bands\": \"precipitationCal\",\n",
    "    \"palette\": [\"000096\", \"0064ff\", \"00b4ff\", \"eb1e00\", \"af0000\"],\n",
    "}\n",
    "\n",
    "# Display the first image in the clipped collection\n",
    "image = ee.Image(clipped_imerg_collection.first())\n",
    "m.addLayer(image, vis_params, \"First image\")\n",
    "m"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 355
    },
    "id": "T4Nv-gzQtPPX",
    "outputId": "cea49cc0-0966-4376-bf29-c50c5d96052e"
   },
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "import cartopy.crs as ccrs\n",
    "import json\n",
    "\n",
    "# import the cartoee functionality from geemap\n",
    "from geemap import cartoee\n",
    "\n",
    "# set the width and height of the map\n",
    "w = 25\n",
    "h = 10\n",
    "\n",
    "# set the center of the map\n",
    "lon = 118\n",
    "lat = -3\n",
    "\n",
    "# set the region of interest\n",
    "region = [lon + w, lat - h, lon - w, lat + h]\n",
    "\n",
    "\n",
    "# use cartoee to get a map\n",
    "ax = cartoee.get_map(image, region=region, vis_params=vis_params)\n",
    "\n",
    "# add the Indonesia boundary to the map\n",
    "outline_style = {\"color\": \"FF0000\", \"width\": 2, \"fillColor\": \"00000000\"}\n",
    "cartoee.add_layer(\n",
    "    ax, indonesia.style(**outline_style), region=region, crs=ccrs.PlateCarree()\n",
    ")\n",
    "\n",
    "# add gridlines to the map at a specified interval\n",
    "cartoee.add_gridlines(ax, interval=[5, 5], linestyle=\":\")\n",
    "\n",
    "# add a colorbar to the map (right side)\n",
    "cb = cartoee.add_colorbar(\n",
    "    ax, vis_params, loc=\"right\", label=\"Rainfall (mm)\", orientation=\"vertical\"\n",
    ")\n",
    "\n",
    "# add north arrow\n",
    "north_arrow_dict = {\n",
    "    \"text\": \"N\",\n",
    "    \"xy\": (0.1, 0.21),\n",
    "    \"arrow_length\": 0.10,\n",
    "    \"text_color\": \"black\",\n",
    "    \"arrow_color\": \"white\",\n",
    "    \"fontsize\": 10,\n",
    "    \"width\": 5,\n",
    "    \"headwidth\": 10,\n",
    "    \"ha\": \"center\",\n",
    "    \"va\": \"center\",\n",
    "}\n",
    "cartoee.add_north_arrow(ax, **north_arrow_dict)\n",
    "\n",
    "# add scale bar\n",
    "scale_bar_dict = {\n",
    "    \"length\": 100,\n",
    "    \"xy\": (0.1, 0.05),\n",
    "    \"linewidth\": 2,\n",
    "    \"fontsize\": 8,\n",
    "    \"color\": \"black\",\n",
    "    \"unit\": \"km\",\n",
    "    \"ha\": \"center\",\n",
    "    \"va\": \"bottom\",\n",
    "}\n",
    "cartoee.add_scale_bar_lite(ax, **scale_bar_dict)\n",
    "\n",
    "# add title\n",
    "ax.set_title(label=\"Total Rainfall (2023-07-15)\", fontsize=10)\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 885
    },
    "id": "qx2YOm0aHZUr",
    "outputId": "6de8d91b-1e62-44cb-814a-960fcbecc190"
   },
   "outputs": [],
   "source": [
    "# create a gif of the images in the clipped collection\n",
    "cartoee.get_image_collection_gif(\n",
    "    ee_ic=clipped_imerg_collection,\n",
    "    out_dir=\"./img/gif_images\",\n",
    "    out_gif=\"./img/animation.gif\",\n",
    "    vis_params=vis_params,\n",
    "    region=region,\n",
    "    fps=2,\n",
    "    mp4=True,\n",
    "    grid_interval=(5, 5),\n",
    "    plot_title=\"Indonesia Daily Rainfall\",\n",
    "    date_format=\"YYYY-MM-dd:HH-mm\",\n",
    "    fig_size=(7, 7),\n",
    "    dpi_plot=100,\n",
    "    file_format=\"png\",\n",
    "    overlay_layers=[indonesia],\n",
    "    overlay_styles=[outline_style],\n",
    "    colorbar_dict={\"loc\": \"right\", \"label\": \"Rainfall (mm)\", \"orientation\": \"vertical\"},\n",
    "    north_arrow_dict=north_arrow_dict,\n",
    "    scale_bar_dict=scale_bar_dict,\n",
    "    verbose=True,\n",
    ")"
   ]
  }
 ],
 "metadata": {
  "colab": {
   "provenance": []
  },
  "kernelspec": {
   "display_name": "Python 3",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
